﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ConfApp.Infrastructure;
using ConfApp.Models;
using ConfApp.Services;
using System.Windows.Navigation;
using Microsoft.Phone.Net.NetworkInformation;
using Microsoft.Practices.Prism.Commands;

namespace ConfApp.ViewModels
{
    public class SpeakerDetailsViewModel : ViewModel
    {
        private readonly IConfDataStoreLocator _confDataStoreLocator;

        private ObservableCollection<GroupList<SessionInfoViewModel>> _observableSpeakerSessionInfoGroups;
        private CollectionViewSource _speakerSessionInfoGroupsViewSource;

        public SpeakerDetailsViewModel(
            IConfDataStoreLocator confDataStoreLocator, 
            INavigationService navigationService) 
            : base(navigationService)
        {
            _confDataStoreLocator = confDataStoreLocator;
            Initialize();
        }

        private void Initialize()
        {
            this.SessionSelectedCommand = new DelegateCommand<SessionInfoViewModel>(
                s =>
                {
                    NavigationService.Navigate(
                        new Uri("/Views/SessionDetailsView.xaml?ID=" + s.ID, UriKind.Relative));
                });
            this.IsBeingActivated();
        }

        private static string SlotInfo(Session session)
        {
            return string.Format("{0} {1}", session.Slot.Day.Index==0?"sre.":"čet.", session.Slot.ToTimeSpanString());
        }

        private List<GroupList<SessionInfoViewModel>> GroupSessions(IEnumerable<Session> sessions)
        {
            var result = new List<GroupList<SessionInfoViewModel>>();
            var slots = sessions.OrderBy(s=>s.Slot.Day.Date).ThenBy(s => s.Slot.ToTimeSpanString()).ThenBy(s => s.Track.Code).Select(s => SlotInfo(s)).Distinct();
            var sessionInfos = sessions.OrderBy(s => s.Slot.Day.Date).ThenBy(s => s.Slot.ToTimeSpanString()).ThenBy(s => s.Track.Code).Select(s => new SessionInfoViewModel(s, NavigationService));
            var groups = new Dictionary<string, GroupList<SessionInfoViewModel>>();
            foreach (var slot in slots)
            {
                var group = new GroupList<SessionInfoViewModel>(slot);
                result.Add(group);
                groups[slot] = group;
            }
            foreach (var sessionInfo in sessionInfos)
            {
                groups[SlotInfo(sessionInfo.Session)].Add(sessionInfo);
            }
            return result;
        }

        private int? _id;
        private Speaker _speaker;
        public Speaker Speaker
        {
            get
            {
                var id = int.Parse(NavigationService.CurrentSource
                                       .OriginalString.Split('=')[1]);
                if(_id == null || (_id != id))
                {
                    _id = id;
                    _speaker = _confDataStoreLocator.GetStore().FindSpeaker(id);
                }
                return _speaker;
            }
        }

        public string FullName { get { return Speaker.FullName.Replace(" ",
            System.Environment.NewLine); } }
        public string Employer { get { return Speaker.Employer; } }

        public BitmapImage Picture
        {
            get
            {
                if(Speaker.Picture != null)
                {
                    var image = new BitmapImage();
                    image.SetSource(new MemoryStream(Speaker.Picture));
                    return image;
                }
                var fileName = System.IO.Path.GetFileName(Speaker.QualifiedUrl);
                var sr = Application.GetResourceStream(new Uri(@"Resources/SpeakerPictures/" + fileName, UriKind.Relative));
                if (sr != null)
                {
                    return new BitmapImage(new Uri(@"\Resources\SpeakerPictures\" + fileName, UriKind.RelativeOrAbsolute));
                }
                if(NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
                {
                    return new BitmapImage(new Uri(Speaker.QualifiedUrl, UriKind.RelativeOrAbsolute));
                }
                return new BitmapImage(new Uri(@"\Resources\SpeakerPictures\no-pic.png",UriKind.RelativeOrAbsolute));
            }
        }

        //public string PictureUrl { get { return Speaker.PictureUrl; } }
        
        public string Bio { get { return Speaker.Bio.Replace("\n", 
            System.Environment.NewLine); } }

        public ICollectionView SpeakerSessionInfos
        {
            get
            {
                _observableSpeakerSessionInfoGroups = new ObservableCollection<GroupList<SessionInfoViewModel>>();
                var speakerSessionInfoViewModelGroups = GroupSessions(Speaker.Sessions);
                speakerSessionInfoViewModelGroups.ForEach(_observableSpeakerSessionInfoGroups.Add);

                _speakerSessionInfoGroupsViewSource = new CollectionViewSource { Source = _observableSpeakerSessionInfoGroups };
                _speakerSessionInfoGroupsViewSource.View.MoveCurrentToPrevious();
                return _speakerSessionInfoGroupsViewSource.View;
            }
        }

        public DelegateCommand<SessionInfoViewModel> SessionSelectedCommand { get; set; }

        public override void IsBeingActivated()
        {
        }

    }
}
